package com.qigao.mall.web.controller.admin.merchant;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.qigao.mall.api.ItemService;
import com.qigao.mall.commons.dto.*;
import com.qigao.mall.commons.enums.PicLocationEnum;
import com.qigao.mall.commons.enums.Result;
import com.qigao.mall.commons.enums.ResultCode;
import com.qigao.mall.commons.enums.StatusCharEnum;
import com.qigao.mall.commons.exceptions.BusinessException;
import com.qigao.mall.web.controller.app.user.AppItemController;
import com.qigao.mall.web.utils.RequestUtils;
import com.qigao.mall.web.utils.ValidatorUtil;
import com.qigao.mall.web.vo.app.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/admin/item/")
@Api(tags = "Admin商户操作商品相关API" ,value = "Admin商户操作商品相关API")
public class AdminItemController extends AppItemController {

    private static Logger logger= LoggerFactory.getLogger(AdminItemController.class);
    @Resource
    ItemService itemService;

    //5.某个店铺内按照状态查询商品信息
    @PostMapping("/findGoodsByStatus/{shopNo}/{status}")
    @ApiOperation(value = "按照状态查询商品信息", notes = "按照状态查询商品信息 1已发布 0已下架")
    public Result<List<ItemResultDto>> findGoodsByStatus(@PathVariable("shopNo")String shopNo,@PathVariable("status")String status){
        try{
            //参数校验
            return itemService.findGoodsByStatus(shopNo,status);
        }catch (Exception e){
            logger.error("[按照状态查询商品信息]发生异常:{}",e);
            return Result.newError(ResultCode.FAIL);
        }
    }

    //4.添加商品
    @PostMapping("/addGoods")
    @ApiOperation(value = "添加商品", notes = "添加商品")
    public Result<String> addGoods(@RequestBody ItemCreateVo itemCreateVo, HttpServletRequest request){
        //参数校验
        ValidatorUtil.validateEntity(itemCreateVo,ItemCreateVo.class);
        try{
            ItemUpdateDto itemCreateDto=new ItemUpdateDto();
            BeanUtils.copyProperties(itemCreateVo,itemCreateDto);
            itemCreateDto.setItemPicDtos(null);
            if(CollectionUtils.isEmpty(itemCreateVo.getItemPicTopVos())){
                throw new BusinessException(ResultCode.COMMON_PARAM_INVALID);
            }
            List<ItemPicDto> itemPicDtos=new ArrayList<ItemPicDto>();
            for(ItemPicVo itemPicVo:itemCreateVo.getItemPicTopVos()){
                ItemPicDto itemPicDto=new ItemPicDto();
                BeanUtils.copyProperties(itemPicVo,itemPicDto);
                itemPicDto.setPicLocation(PicLocationEnum.TOP.getCode());
                itemPicDtos.add(itemPicDto);
            }
            if(!CollectionUtils.isEmpty(itemCreateVo.getItemPicDetailVos())){
                for(ItemPicVo itemPicVo:itemCreateVo.getItemPicDetailVos()){
                    ItemPicDto itemPicDto=new ItemPicDto();
                    BeanUtils.copyProperties(itemPicVo,itemPicDto);
                    itemPicDto.setPicLocation(PicLocationEnum.DETAIL.getCode());
                    itemPicDtos.add(itemPicDto);
                }
            }
            itemCreateDto.setItemPicDtos(itemPicDtos);
            itemCreateDto.setItemSkuDtos(null);
            List<ItemSkuDto> itemSkuDtos=new ArrayList<>();
            if(!CollectionUtils.isEmpty(itemCreateVo.getItemSkuCreateVos())){
                for(ItemSkuCreateVo itemSkuCreateVo:itemCreateVo.getItemSkuCreateVos()){
                    ItemSkuDto itemSkuDto=new ItemSkuDto();
                    BeanUtils.copyProperties(itemSkuCreateVo,itemSkuDto);
                    itemSkuDtos.add(itemSkuDto);
                }
                itemCreateDto.setItemSkuDtos(itemSkuDtos);
            }
            itemCreateDto.setUserNo(RequestUtils.getCurrentUserNo(request));
            itemService.addGoods(itemCreateDto);
            return Result.newSuccess();
        }catch (BusinessException be){
            logger.error("[添加商品]发生业务异常:{}",be);
            return Result.newError(be.getCode(),be.getMsg());
        }catch (Exception e){
            logger.error("[添加商品]发生异常:{}",e);
            return Result.newError(ResultCode.FAIL);
        }
    }

    //5.修改商品信息
    @PostMapping("/modiGoods")
    @ApiOperation(value = "修改商品", notes = "修改商品")
    public Result<String> modiGoods(@RequestBody ItemModiVo itemModiVo, HttpServletRequest request){
        try{
            //参数校验
            ValidatorUtil.validateEntity(itemModiVo,ItemModiVo.class);
            ItemUpdateDto itemUpdateDto=new ItemUpdateDto();
            BeanUtils.copyProperties(itemModiVo,itemUpdateDto);
            itemUpdateDto.setItemPicDtos(null);
            if(CollectionUtils.isEmpty(itemModiVo.getItemPicTopVos())){
                throw new BusinessException(ResultCode.COMMON_PARAM_INVALID);
            }
            List<ItemPicDto> itemPicDtos=new ArrayList<ItemPicDto>();
            for(ItemPicModiVo itemPicVo:itemModiVo.getItemPicTopVos()){
                ItemPicDto itemPicDto=new ItemPicDto();
                BeanUtils.copyProperties(itemPicVo,itemPicDto);
                if(!StringUtils.isEmpty(itemPicVo.getId()))
                    itemPicDto.setId(Integer.valueOf(itemPicVo.getId()));
                itemPicDto.setPicLocation(PicLocationEnum.TOP.getCode());
                itemPicDtos.add(itemPicDto);
            }
            if(!CollectionUtils.isEmpty(itemModiVo.getItemPicDetailVos())){
                for(ItemPicModiVo itemPicVo:itemModiVo.getItemPicDetailVos()){
                    ItemPicDto itemPicDto=new ItemPicDto();
                    BeanUtils.copyProperties(itemPicVo,itemPicDto);
                    if(!StringUtils.isEmpty(itemPicVo.getId()))
                    itemPicDto.setId(Integer.valueOf(itemPicVo.getId()));
                    itemPicDto.setPicLocation(PicLocationEnum.DETAIL.getCode());
                    itemPicDtos.add(itemPicDto);
                }
            }
            itemUpdateDto.setItemPicDtos(itemPicDtos);
            itemUpdateDto.setItemSkuDtos(null);
            List<ItemSkuDto> itemSkuDtos=new ArrayList<>();
            if(!CollectionUtils.isEmpty(itemModiVo.getItemSkuModiVos())){
                for(ItemSkuModiVo itemSkuModiVo:itemModiVo.getItemSkuModiVos()){
                    ItemSkuDto itemSkuDto=new ItemSkuDto();
                    BeanUtils.copyProperties(itemSkuModiVo,itemSkuDto);
                    itemSkuDtos.add(itemSkuDto);
                }
                itemUpdateDto.setItemSkuDtos(itemSkuDtos);
            }
            itemUpdateDto.setUserNo(RequestUtils.getCurrentUserNo(request));
            itemService.modiGoods(itemUpdateDto);
            return Result.newSuccess();
        }catch (BusinessException be){
            logger.error("[修改商品]发生业务异常:{}",be);
            return Result.newError(be.getCode(),be.getMsg());
        } catch (Exception e){
            logger.error("[修改商品]发生异常:{}",e);
            return Result.newError(ResultCode.FAIL);
        }
    }

    //5.商品上架或下架
    @PostMapping("/upOrDown/{itemNo}")
    @ApiOperation(value = "商品上架或下架", notes = "商品上架或下架")
    public Result<String> upOrDown(@PathVariable("itemNo")String itemNo){
        try{
            //参数校验
            itemService.upOrDown(itemNo);
            return Result.newSuccess();
        }catch (Exception e){
            logger.error("[商品上架或下架]发生异常:{}",e);
            return Result.newError(ResultCode.FAIL);
        }
    }

    //5.删除商品信息
    @PostMapping("/delGoods/{itemNo}")
    @ApiOperation(value = "删除商品信息", notes = "删除商品信息")
    public Result<String> delGoods(@PathVariable("itemNo")String itemNo){
        try{
            //参数校验
            itemService.deleteByItemNo(itemNo);
            return Result.newSuccess();
        }catch (Exception e){
            logger.error("[删除商品信息]发生异常:{}",e);
            return Result.newError(ResultCode.FAIL);
        }
    }


    /**
     * 按照分类、上下架状态显示商品
     * @return
     */
    @GetMapping("/findItemByCatNo/{catNo}/{status}")
    @ApiOperation(value = "按照分类显示已上/下架商品", notes = "按照分类显示已上/下架商品 status:1已发布 0已下架")
    public Result<List<ItemResultDto>> showItemByCatNoAndStatus(@PathVariable("catNo")String catNo,@PathVariable("status")String status){
        try{
            if(StringUtils.isEmpty(status)){
                status="1";
            }
            List<ItemResultDto> itemResultDtos =itemService.showItemByCatNo(catNo,status);
            if(itemResultDtos !=null && itemResultDtos.size()>=1){
                return Result.newSuccess(itemResultDtos);
            }
            return Result.newError(ResultCode.COMMON_DATA_NOT_EXISTS);
        }catch (Exception e){
            logger.error("[商品分类]发生异常:{}",e);
            return Result.newError(ResultCode.FAIL);
        }
    }

    @RequestMapping(value = "listPage", method = RequestMethod.POST)
    @ApiOperation(value = "商品分页查询", notes = "商品分页查询")
    @ApiParam(name = "itemQueryPageVo", value = "商品分页查询", required = true)
    public Result<PageInfo<ItemResultDto>> listPage(@RequestBody ItemQueryPageVo itemQueryPageVo) {
        try{
            ItemQueryPageDto itemQueryPageDto=new ItemQueryPageDto();
            BeanUtils.copyProperties(itemQueryPageVo,itemQueryPageDto);
            Page<ItemResultDto> itemResultDtoPage =itemService.search(itemQueryPageDto);
            if(itemResultDtoPage !=null && itemResultDtoPage.getResult().size()>=1){
                PageInfo<ItemResultDto> itemResultDtoPageInfo = new PageInfo(itemResultDtoPage);
                return Result.newSuccess(itemResultDtoPageInfo);
            }
            return Result.newSuccess();
        }catch (Exception e){
            logger.error("[商品搜索]发生异常:{}",e);
            return Result.newError(ResultCode.FAIL);
        }
    }

}
